<template>

  <a-modal :open="open" :title="title" @ok="handleOk" @cancel="cancel" okText="确定" cancelText="取消">
    <a-form :model="userForm" v-bind="layout" ref="userFormRef">
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="userForm.username" />
      </a-form-item>
      <a-form-item label="联系方式"  name="mobile">
        <a-input v-model:value="userForm.mobile" />
      </a-form-item>
      <a-form-item label="性别" name="sex">
        <a-select ref="select" v-model:value="userForm.sex" style="width: 100%;">
          <a-select-option v-for="(item, index) in sexArr" :value="item.value">{{ item.name }}</a-select-option>


        </a-select>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-input v-model:value="userForm.status" />
      </a-form-item>
      <a-form-item label="角色" name="status">
      <a-select
    v-model:value="userForm.roleIds"
    mode="multiple"
    :field-names="{ label: 'name', value: 'value', options: 'children' }"
    style="width: 100%"
    placeholder="Please select"
    :options="roles"
    @change="handleChange"
  ></a-select>
</a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup name="UserModal">
import { useDictStore } from '@/stores/dict'
import { addUser,updateUser } from '@/api/user';
import { option } from '@/api/role';
import { message } from 'ant-design-vue';
import { ref } from 'vue';
const dictStroe = useDictStore();
//定义弹框关闭 页面要刷新
const emit = defineEmits(['refresh'])
const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 16,
  },
};
//弹框的开关
const open = ref(false)
//标题
const title=ref('新增')
//表单对象
const userForm = reactive(
  {
    id:'',
    username: '',
    sex: '',
    mobile: '',
    status: '',
    roleIds:[]
  }
);
const roles=ref([]);
//表单对象 用于清空表单数据
const userFormRef = ref();
//弹框类型 默认是新增
const type=ref(true)
// 下拉框选中数据
const sexArr = computed(() => dictStroe.state.dicts)
//设置弹框的开闭 第一个参数是否是是新增  第二个参数是数据
const openModal =async (isNew=true,data)=>{

   const res = await option()
   roles.value = res.data;
  open.value = true;
  if(!isNew && data){
    title.value = '编辑';
    type.value=false;
    for(const key in userForm){
      userForm[key]=data[key]
    }
  }else{
    type.value=true;
    title.value = '新建'
  }
}
//关闭弹框
const cancel = e => {
  open.value = false
  userFormRef.value.resetFields();
}
//提交
const handleOk = async e => {
  if(type.value){
    await addUser(userForm)
  }else{
    await updateUser(userForm)
  }

  message.success({
    content:"成功",
    duration:1,
    onClose:()=>{
      userFormRef.value.resetFields();
      open.value= false;
      emit('refresh')
    }
  })  
};

const handleChange = value => {
  console.log(`selected ${value}`);
};
//在这里暴露这个方法 在外面调用
defineExpose({ openModal })

</script>

<style scoped>
.ant-form {
  margin-top: 36px;
}
</style>